package com.nameless.service;

import com.nameless.entity.Menu;
import com.nameless.entity.Users;
import com.nameless.feign.AdminFeign;
import com.nameless.feign.PermissionFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author keluoyisi
 * @program: tong-parent
 * @description:
 * @date 2023-02-23 21:19:17
 */
@Service
public class UsernameService implements UserDetailsService {
    @Autowired
    private AdminFeign adminFeign;

    @Autowired
    private PermissionFeign permissionFeign;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users admin = adminFeign.getAdmin(username);
        System.out.println(admin);
        if (admin!=null){
            List<Menu> permissions = permissionFeign.getPermissionByUserId(admin.getUserId());
            List<SimpleGrantedAuthority> collect = permissions.stream()
                    .filter(item -> item.getPerms() != null)
                    .filter(item-> StringUtils.hasText(item.getPerms()))
                    .map(item -> new SimpleGrantedAuthority(item.getPerms()))
                    .collect(Collectors.toList());
            System.out.println(collect);
            User user = new User(admin.getUserName(), admin.getPassword(), collect);
            return user;
        }

        return null;
    }
}
